package com.youjiang.meeting.controller;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpSession;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.context.ContextLoader;

import com.youjiang.meeting.mapper.WxconfigMapper;
import com.youjiang.meeting.po.UserInfo;
import com.youjiang.meeting.po.Wxconfig;
import com.youjiang.meeting.po.WxconfigExample;
import com.youjiang.meeting.utils.GetHttpSessionConfigurator;

import net.sf.json.JSONObject;




/**
 * <p>
 * Title: SendInformationSocket
 * </p> 
 * <p>
 * Description:TODO
 * </p> 
 * <p>
 * Company: YouJiang
 * </p> 
 */
/**
 * 在微信墙那边获取用户的ID然后将用户ID作为119.23.71.112/meeting/information的参数传递到该类中
 * 这样可以区分每一个用户的粉丝发的信息只会发到他们的弹幕墙中
 * @author Administrator
 *
 */
@ServerEndpoint(value="/information/{originid}",configurator=GetHttpSessionConfigurator.class)
public class SendInformationSocket {
	
	private HttpSession httpSession;
	private Session session;
	private static String originid;
	private WxconfigMapper mapper = ContextLoader.getCurrentWebApplicationContext().getBean(WxconfigMapper.class);

	
	private static Set<SendInformationSocket> informationSocket;
	static{
		informationSocket=new HashSet<SendInformationSocket>();
	}

	public SendInformationSocket() {
		// TODO Auto-generated constructor stub
		System.out.println("SendInformationSocket------------");
	}

	@OnOpen
	public void onOpen(@PathParam("originid")String origin, Session session,EndpointConfig config) {
		
		HttpSession httpSession= (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        System.out.println("websocket userInfo:"+httpSession.getAttribute("userInfo"));
        UserInfo info = (UserInfo) httpSession.getAttribute("userInfo");
        System.out.println("info>>>>>>"+info);
        /**
         * 获取登录的用户
         */
        WxconfigExample example = new WxconfigExample();
        WxconfigExample.Criteria criteria = example.createCriteria();
        criteria.andOriginidEqualTo(origin);
        List<Wxconfig> list = mapper.selectByExample(example);
        if(list!=null && list.size()>0){
        	Wxconfig wxconfig = list.get(0);
        	int userid = wxconfig.getUserid();
        	/**
        	 * 
        	 * 判断当前客户端登录的用户是否为空以及登录用户的ID是否与微信墙那边传递过来的ID是否相等
        	 * 
        	 */
        	if(info!=null && info.getId().equals(userid)){
            	this.session = session;
                this.httpSession = httpSession;
                System.out.println("httpSession>>>"+httpSession);
                WxconfigExample wexample = new WxconfigExample();
                WxconfigExample.Criteria wcriteria = example.createCriteria();
                wcriteria.andUseridEqualTo(info.getId());
                List<Wxconfig> configList = mapper.selectByExample(wexample);
                System.out.println("configList>>>"+configList.size());
                if(configList!=null && configList.size()>0){
                	Wxconfig wconfig = configList.get(0);
                	originid = wconfig.getOriginid();            	
                }
                System.out.println("originid>>>>>>"+originid);
                System.out.println("info--"+info);
                System.out.println("------------有人接进来了");
        		try {
        			synchronized (informationSocket) {
        				informationSocket.add(this);
        			}
        		} catch (Exception e) {
        			e.printStackTrace();
        		}
            }
        }
        
	}
	@OnMessage
	public  void receive(Session  session,String msg){
		System.out.println("用户的sessionId:"+session.getId());
		System.out.println("客户端发送过来的消息:"+msg);
		
		send(msg);
	}
	
	@OnClose
	public void onClose(Session session){
		synchronized (informationSocket) {
			informationSocket.remove(this);	
			System.out.println("有连接关闭");
		}
	}
	
	@OnError
	public void error(Throwable t){
		System.out.println("websocket error------"+t.getMessage());
	}
	public static void send(String info) {
		System.out.println("info---***:"+info);
		if(!StringUtils.isEmpty(info)){
			synchronized (informationSocket) {
				System.out.println("informationSocket:"+informationSocket.size());
				for(SendInformationSocket it:informationSocket){
					
					try{
						
					    System.out.println("it.getSession().getBasicRemote()"+it.getSession().getBasicRemote());
					    System.out.println("info------"+info);	
					    JSONObject object = JSONObject.fromObject(info);
					    String toUser = (String) object.opt("origined");
					    System.out.println("*********************");
					    System.out.println("toUser>>"+toUser);
					    /**
					     * 
					     * 只有该公众号下的粉丝才能发送消息到弹幕墙
					     * 
					     */
					    if(StringUtils.isNotBlank(originid) && StringUtils.isNotBlank(toUser)){
					    	if(originid.equals(toUser)){
						    	System.out.println("originid>>"+originid);
						 
						    	it.getSession().getBasicRemote().sendText(info);
						    }
					    }
					    
					    	
					}catch(Exception e){
						e.printStackTrace();
					}
					
				}
			}
		}
		
	}

	public Session getSession() {
		return session;
	}
}
